package com.zsummer.design.structure.composite;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 组合模式
 * @author zsummer
 */
public class Client {
    public static void main(String[] args) {
        Element root = new Element(1);

        Element leaf1 = new Element(2);
        Element leaf2 = new Element(3);

        root.addChild(leaf1);
        root.addChild(leaf2);

        System.out.println(root.getChildren());

        root.removeChild(2);

        System.out.println(root.getChildren());
    }
}

class Element {
    int id;
    List<Element> children = new ArrayList<>();

    public Element(int id) {
        this.id = id;
    }

    public void addChild(Element element) {
        children.add(element);
    }

    public void removeChild(int id) {
        Iterator<Element> iterator = children.iterator();
        while (iterator.hasNext()) {
            Element element = iterator.next();
            if (element.getId() == id) {
                iterator.remove();
            }
        }
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public List<Element> getChildren() {
        return children;
    }

    public void setChildren(List<Element> children) {
        this.children = children;
    }

    @Override
    public String toString() {
        return "Element{" +
                "id=" + id +
                ", children=" + children +
                '}';
    }
}
